<template>


  <div id="userList">

    <el-row>
      <!-- 左边部门树 -->
      <el-col :span="6">
        <div class="grid-content gridLeft">
          <h4>部门管理</h4>
          <el-row>
            <div class="userHandle">
              <el-button type="primary" icon="el-icon-circle-plus-outline" round @click.native="openAddDept"
                         size="mini">
                新增
              </el-button>
              <el-button type="success" icon="el-icon-edit" round @click.native="openUpdateDept" size="mini">修改
              </el-button>
              <el-button type="danger" icon="el-icon-delete" round @click.native="deleteDept" size="mini">删除</el-button>
            </div>
          </el-row>
          <el-tree :data="deptTreeData" :props="deptProps" @node-click="deptTreeClick"
                   default-expand-all highlight-current></el-tree>
        </div>
      </el-col>
      <!-- 右边用户列表 -->
      <el-col :span="18">
        <div class="grid-content gridRight">
          <h4>用户管理</h4>
          <!-- 列表工具栏 -->
          <el-row class="userHandle">
            <div class="cf handleLeft">
              <el-button type="primary" icon="el-icon-circle-plus-outline" round @click.native="openAddUser"
                         size="mini">
                新增
              </el-button>
              <el-button type="success" icon="el-icon-edit" round @click.native="openUpdateUser" size="mini">修改
              </el-button>
              <el-button type="danger" icon="el-icon-delete" round @click.native="deleteUser" size="mini">删除
              </el-button>
              <el-button type="primary" icon="el-icon-edit-outline" round @click.native="openRoleDialog" size="mini">
                分配角色
              </el-button>
              <el-button type="warning" icon="el-icon-info" round @click.native="resetUserPassword" size="mini">重设密码
              </el-button>
            </div>
            <div class="cf handleRight">
              <el-input v-model="searchUserName" placeholder="请输入用户名称" clearable>
              </el-input>
              <el-button type="primary" icon="el-icon-search" round @click.native="searchUserList" size="mini">搜索
              </el-button>
              <el-button type="info" icon="el-icon-refresh" round @click.native="resetUserList" size="mini">重置
              </el-button>
            </div>
          </el-row>

          <!-- 用户列表数据 -->
          <el-table
            :data="userDataList"
            style="width: 100%" highlight-current-row @row-click="userListClick">
            <el-table-column
              prop="sysUserAccount"
              label="用户账号"
              align="center">
            </el-table-column>
            <el-table-column
              prop="sysUserName"
              label="用户名称"
              align="center">
            </el-table-column>
            <el-table-column
              prop="sysDept"
              label="所属部门"
              :formatter="formatSystemDeptName"
              align="center">
            </el-table-column>
            <el-table-column
              prop="isLockedStr"
              label="是否可用"
              align="center"
              :formatter="formatIsLocked">
            </el-table-column>
          </el-table>
          <el-pagination
            layout="prev, pager, next"
            :page-sizes="[5]"
            :page-size="userListPageSize"
            :total="userListPageTotal"
            @current-change="currentChangeUserListPage">
          </el-pagination>
        </div>
      </el-col>
    </el-row>

    <!-- 部门弹窗 -->
    <el-dialog title="部门信息" :visible.sync="deptInfoDialog">
      <el-form :model="deptForm" ref="deptForm" label-position="left">
        <el-form-item label="部门名称" :label-width="formLabelWidth" prop="sysDeptName"
                      :rules="{required: true, message: '部门名称不能为空', trigger: 'blur'}">
          <el-input v-model="deptForm.sysDeptName" autocomplete="off" placeholder="部门名称"></el-input>
        </el-form-item>
        <el-form-item label="上级部门" :label-width="formLabelWidth" prop="sysDeptParentId"
                      :rules="{required: true, message: '请选择上级部门', trigger: 'blur'}">
          <el-select v-model="deptForm.sysDeptParentId" placeholder="请选择上级部门"
                     :disabled="deptForm.sysDeptNameFlag" style="width:100%;">
            <el-option
              v-for="item in parentDeptList"
              :key="item.sysDeptId"
              :label="item.sysDeptName"
              :value="item.sysDeptId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门排序" :label-width="formLabelWidth">
          <el-input v-model="deptForm.sysDeptSort" autocomplete="off" placeholder="部门排序"></el-input>
        </el-form-item>
        <el-form-item label="部门备注" :label-width="formLabelWidth">
          <el-input v-model="deptForm.sysDeptRemark" autocomplete="off" placeholder="部门备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deptInfoDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdateDept('deptForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新增-用户弹窗 -->
    <el-dialog title="用户信息" :visible.sync="addUserInfoDialog">
      <el-form :model="addUserForm" ref="addUserForm" label-position="left">
        <el-form-item label="用户名称" :label-width="formLabelWidth" prop="sysUserName"
                      :rules="{required: true, message: '用户名称不能为空', trigger: 'blur'}">
          <el-input v-model="addUserForm.sysUserName" autocomplete="off" placeholder="用户名称"></el-input>
        </el-form-item>
        <el-form-item label="用户账号" :label-width="formLabelWidth" prop="sysUserAccount"
                      :rules="{required: true, message: '用户账号不能为空', trigger: 'blur'}">
          <el-input v-model="addUserForm.sysUserAccount" autocomplete="off" placeholder="用户账号"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" :label-width="formLabelWidth" prop="sysUserPassword"
                      :rules="{required: true, message: '用户密码不能为空', trigger: 'blur'}">
          <el-input type="password" v-model="addUserForm.sysUserPassword" autocomplete="off"
                    placeholder="用户密码"></el-input>
        </el-form-item>
        <el-form-item label="所属部门" :label-width="formLabelWidth">
          <el-input v-model="addUserForm.sysDeptName" autocomplete="off" placeholder="所属部门"
                    :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="是否可用" :label-width="formLabelWidth" prop="isLocked"
                      :rules="{required: true, message: '账号状态不能为空', trigger: 'blur'}">
          <el-radio-group v-model="addUserForm.isLocked">
            <el-radio :label="1">可用</el-radio>
            <el-radio :label="2">锁定</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户备注" :label-width="formLabelWidth">
          <el-input v-model="addUserForm.sysUserRemark" autocomplete="off" placeholder="用户备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addUserInfoDialog = false">取 消</el-button>
        <el-button type="primary" @click="addUser('addUserForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改-用户弹窗 -->
    <el-dialog title="用户信息" :visible.sync="updateUserInfoDialog">
      <el-form :model="updateUserForm" ref="updateUserForm" label-position="left">
        <el-form-item label="用户名称" :label-width="formLabelWidth" prop="sysUserName"
                      :rules="{required: true, message: '用户名称', trigger: 'blur'}">
          <el-input v-model="updateUserForm.sysUserName" autocomplete="off" placeholder="用户名称"></el-input>
        </el-form-item>
        <el-form-item label="用户账号" :label-width="formLabelWidth">
          <el-input v-model="updateUserForm.sysUserAccount" autocomplete="off" placeholder="用户账号"
                    :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="所属部门" :label-width="formLabelWidth">
          <el-input v-model="updateUserForm.sysDeptName" autocomplete="off" placeholder="所属部门"
                    :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="是否可用" :label-width="formLabelWidth" prop="isLocked">
          <el-radio-group v-model="updateUserForm.isLocked">
            <el-radio :label="1">可用</el-radio>
            <el-radio :label="2">锁定</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户备注" :label-width="formLabelWidth">
          <el-input v-model="updateUserForm.sysUserRemark" autocomplete="off" placeholder="用户备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateUserInfoDialog = false">取 消</el-button>
        <el-button type="primary" @click="updateUser('updateUserForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色弹窗 -->
    <el-dialog title="角色信息" :visible.sync="roleDialog">
      <el-select v-model="roleId" placeholder="请选择角色">
        <el-option
          v-for="item in roleList"
          :key="item.sysRoleId"
          :label="item.sysRoleName"
          :value="item.sysRoleId">
        </el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveUserRelRole">确 定</el-button>
      </div>
    </el-dialog>

  </div>


</template>


<script>
  import api from "@/assets/js/system/user_list.js";
  import common from "@/assets/js/common/common.js";

  export default {
    data() {
      return {
        userDataList: [],//用户数据列表
        userListPageTotal: 0,//用户列表总数
        userListPageSize: 10, //用户每页显示的数据量
        userListPageNo: 1,//用户分页的当前页
        deptTreeData: [],//树形部门数据
        //树形部门定义的格式对应关系
        deptProps: {
          children: 'children',
          label: 'text'
        },
        deptInfoDialog: false, //部门窗口状态属性
        parentDeptList: [],//父级部门List
        //部门信息表单
        deptForm: {
          sysDeptId: null,
          sysDeptName: null,
          //上级部门是否可选用  false 可用 true 不可用
          sysDeptNameFlag: false,
          sysDeptParentId: null,
          sysDeptSort: null,
          sysDeptRemark: null
        },
        formLabelWidth: '120px', //全部form宽度
        //用户列表搜索变量
        searchUserName: "",
        addUserInfoDialog: false, //新增用户信息窗口状态属性
        updateUserInfoDialog: false, //更新用户信息窗口状态属性
        //新增用户信息表单
        addUserForm: {
          sysUserId: null,
          sysDeptId: null,
          sysDeptName: null,
          sysUserAccount: null,
          sysUserPassword: null,
          sysUserName: null,
          isLocked: null,
          sysUserRemark: null
        },
        //更新用户信息表单
        updateUserForm: {
          sysUserId: null,
          sysDeptId: null,
          sysDeptName: null,
          sysUserAccount: null,
          sysUserName: null,
          isLocked: null,
          sysUserRemark: null
        },
        roleDialog: false, // 角色信息弹窗
        roleId: null, //角色id
        roleList: [] //角色列表
      }
    },
    mounted: function () {
      //需要执行的方法可以在mounted中进行触发，其获取的数据可以赋到data中后，可以放在前面进行渲染
      this.getUserList({
        pageNo: 1,
        pageSize: this.userListPageSize,
        sysDeptId: this.deptForm.sysDeptId
      });//获取用户分页列表
      this.getDeptTreeList();//获取部门树形数据
      this.getParentDeptList();//获取所有一级部门列表
      this.getRoleList();//获取所有角色列表
    },
    methods: {
      /**
       * 获取用户分页列表数据
       * */
      getUserList(param) {
        api.getUserList(param).then((res) => {
          if (res.data == null || res.data.list == null) {
            this.userDataList = null;
            return;
          }
          this.userDataList = res.data.list;
          this.userListPageTotal = parseInt(res.data.total);//页总数
          this.userListPageNo = parseInt(res.data.pageNum);//当前页
          //重置表单数据
          this.addUserForm = {};
          this.updateUserForm = {};
        });
      },
      /**
       * 分页组件-改变当前页事件监听
       * */
      currentChangeUserListPage(val) {
        this.getUserList({
          pageNo: val,
          pageSize: this.userListPageSize,
          sysDeptId: this.deptForm.sysDeptId
        });
      },
      /**
       * 根据用户列表的数据转换
       * */
      formatIsLocked(row) {
        return this.getLockedEnumMsg(row.isLocked);
      },
      /**
       * 根据部门数据转换成部门名称
       * */
      formatSystemDeptName(row) {
        return row.sysDept.sysDeptName;
      },
      /**
       * 根据枚举值获取锁定状态的枚举信息
       * */
      getLockedEnumMsg(value) {
        var msg = "";
        switch (value) {
          case 1:
            msg = "可用";
            break;
          case 2:
            msg = "锁定";
            break;
          case "1":
            msg = "可用";
            break;
          case "2":
            msg = "锁定";
            break;
          default:
            break;
        }
        return msg;
      },
      /**
       * 搜索用户列表
       * */
      searchUserList() {
        var param = {
          pageNo: 1,
          pageSize: 10,
          sysDeptId: this.deptForm.sysDeptId,
          sysUserName: this.searchUserName
        };
        this.getUserList(param);
      },
      /**
       * 重置用户列表
       * */
      resetUserList() {
        this.searchUserName = "";
        var param = {
          pageNo: 1,
          pageSize: 10,
          sysDeptId: this.deptForm.sysDeptId
        };
        this.getUserList(param);
      },
      /**
       * 获取部门树列表
       * */
      getDeptTreeList() {
        api.getDeptTreeList().then((res) => {
          this.deptTreeData = res.data;
        });
      },
      /**
       * 部门树点击事件
       * */
      deptTreeClick(data) {
        this.getUserList({
          pageNo: 1,
          pageSize: this.userListPageSize,
          sysDeptId: data.id
        });
        //部门表单里面的deptId赋值
        this.deptForm.sysDeptId = data.id;
        this.deptForm.sysDeptName = data.text;
      },
      /**
       * 打开新增部门
       * */
      openAddDept() {
        //清空表单数据
        this.deptForm = {};
        this.getParentDeptList();//更新一级部门数据。
        this.deptInfoDialog = true;

      },
      /**
       * 获取一级部门数据列表并更新
       * */
      getParentDeptList() {
        api.getParentDeptList({}).then((res) => {
          if (res.data == null) {
            this.parentDeptList = null;
            return;
          }
          this.parentDeptList = res.data;
        });
      },
      /**
       * 保存部门信息
       * */
      saveOrUpdateDept(formName) {
        this.$refs[formName].validate((valid) => {
          if (!valid) {
            //console.log('error submit!!');
            return false;
          }
          if (this.deptForm.sysDeptId == null) {
            this.addDept();
          } else {
            this.updateDept();
          }
        });
      },
      /**
       * 新增部门
       * */
      addDept() {
        api.saveDept(this.deptForm).then((res) => {
          this.getDeptTreeList();//重新加载树形数据
          common.generalMessage(res); //提示框信息
          this.deptInfoDialog = false; //关闭弹窗
        });
      },
      /**
       * 根据部门id打开弹窗
       * */
      openUpdateDept() {
        if (this.deptForm.sysDeptId == null) {
          common.message("请选择需要修改的部门", "warning");
          return;
        }
        this.getParentDeptList();//更新一级部门数据。
        //调用部门id获取部门信息接口
        api.findDeptById({
          sysDeptId: this.deptForm.sysDeptId
        }).then((res) => {
          if (res.code != 200) {
            common.generalMessage(res);
            return;
          }
          this.deptForm = res.data;
          if (res.data.sysDeptParentId == "") {
            this.deptForm.sysDeptParentId = "0";
            this.deptForm.sysDeptNameFlag = true;//一级部门不能选择其他部门
          } else {
            this.deptForm.sysDeptNameFlag = false;
          }
          this.deptInfoDialog = true;
        });
      },
      /**
       * 更新部门
       * */
      updateDept() {
        api.updateDept(this.deptForm).then((res) => {
          this.getDeptTreeList();//重新加载树形数据
          common.generalMessage(res); //提示框信息
          this.deptInfoDialog = false; //关闭弹窗
        });
      },
      /**
       * 删除部门
       * */
      deleteDept() {
        if (this.deptForm.sysDeptId == null) {
          common.message("请选择需要删除的部门", "warning");
          return;
        }
        this.$confirm("确认是否删除部门【" + this.deptForm.sysDeptName + "】", "是否继续?", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          api.deleteDept({
            id: this.deptForm.sysDeptId
          }).then((res) => {
            this.getDeptTreeList();//重新加载树形数据
            common.generalMessage(res); //提示框信息
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      },
      /**
       * 用户列表点击事件
       * */
      userListClick(row) {
        this.addUserForm.sysDeptId = row.sysDeptId;

        this.updateUserForm.sysUserId = row.sysUserId;
        this.updateUserForm.sysUserName = row.sysUserName;
        this.updateUserForm.sysDeptId = row.sysDeptId;
      },
      /**
       * 打开新增用户窗口
       * */
      openAddUser() {
        if (this.deptForm.sysDeptId == null) {
          common.message("请选择需要新增用户的部门", "warning");
          return;
        }
        //清空表单数据
        this.addUserForm = {};
        //根据选择的部门信息，显示对应的部门信息
        this.addUserForm.sysDeptId = this.deptForm.sysDeptId;
        this.addUserForm.sysDeptName = this.deptForm.sysDeptName;
        this.addUserInfoDialog = true;
      },
      /**
       * 新增用户
       * */
      addUser(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            api.addUser(this.addUserForm).then((res) => {
              common.generalMessage(res); //提示框信息
              this.resetUserList();//重置当前用户列表
              this.addUserInfoDialog = false; //关闭弹窗
            });
          } else {
            return false;
          }
        });
      },
      /**
       * 打开更新用户信息窗口
       * */
      openUpdateUser() {
        if (this.updateUserForm.sysUserId == null) {
          common.message("请选择你需要修改的用户信息", "warning");
          return;
        }
        api.findUserById({
          sysUserId: this.updateUserForm.sysUserId
        }).then((res) => {
          if (res.code != 200) {
            common.generalMessage(res);
            return;
          }
          this.updateUserForm = res.data;
          //部门名称先从部门表单获取，没有则调用接口获取部门名称
          this.updateUserForm.sysDeptName = this.deptForm.sysDeptName;
          if (this.updateUserForm.sysDeptName != null && this.updateUserForm.sysDeptName != "") {
            //打开弹窗
            this.updateUserInfoDialog = true;
            return;
          }
          //根据部门id获取部门信息
          api.findDeptById({
            sysDeptId: this.updateUserForm.sysDeptId
          }).then((res) => {
            if (res.code != 200) {
              common.generalMessage(res);
              return;
            }
            this.updateUserForm.sysDeptName = res.data.sysDeptName;
            this.updateUserInfoDialog = true; //打开弹窗
          });
        });
      },
      /**
       * 更新用户
       * */
      updateUser(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            api.updateUser(this.updateUserForm).then((res) => {
              common.generalMessage(res); //提示框信息
              this.resetUserList();//重置当前用户列表
              this.updateUserInfoDialog = false; //关闭弹窗
            });
          } else {
//            console.log('error submit!!');
            return false;
          }
        });
      },
      /**
       * 删除用户
       * */
      deleteUser() {
        if (this.updateUserForm.sysUserId == null) {
          common.message("请选择你需要删除的用户信息", "warning");
          return;
        }
        this.$confirm("确认是否删除用户【" + this.updateUserForm.sysUserName + "】", "是否继续?", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          api.deleteUser({
            id: this.updateUserForm.sysUserId
          }).then((res) => {
            common.generalMessage(res); //提示框信息
            this.resetUserList();//重置当前用户列表
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      },
      /**
       * 获取所有角色列表
       * */
      getRoleList() {
        api.getRoleList({}).then((res) => {
          this.roleList = res.data;
        });
      },
      /**
       * 打开分配角色弹窗
       * */
      openRoleDialog() {
        if (this.updateUserForm.sysUserId == null) {
          common.message("请选择你需要分配角色的用户", "warning");
          return;
        }
        api.getRoleByUserId({
          userId: this.updateUserForm.sysUserId
        }).then((res) => {
          if (res.code != 200) {
            common.generalMessage(res);
            return;
          }
          if (res.data[0] == null) {
            this.roleId = null;
            this.roleDialog = true;
            return;
          }
          this.roleId = res.data[0].sysRoleId;
          this.roleDialog = true;
        });

      },
      /**
       * 保存角色分配
       * */
      saveUserRelRole() {
        api.saveUserRelRole({
          userId: this.updateUserForm.sysUserId,
          roleId: this.roleId
        }).then((res) => {
          common.generalMessage(res);
          this.roleDialog = false;
        });
      },
      /**
       * 重设密码
       * */
      resetUserPassword() {
        if (this.updateUserForm.sysUserId == null) {
          common.message("请选择你需要重置密码的用户", "warning");
          return;
        }
        this.$confirm("确认是否重置用户名称【" + this.updateUserForm.sysUserName + "】的密码", "是否继续?", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          api.updatePassword({
            sysUserId: this.updateUserForm.sysUserId
          }).then((res) => {
            this.$alert(res.msg, '新密码', {
              confirmButtonText: '确定'
            });
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      },
      /**
       * 解锁
       * */
      unlock(scope){
        this.$confirm("确认是否解锁用户【" + scope.row.sysUserName + "】并重置错误次数", "是否继续?", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          api.unlock({
            id: scope.row.sysUserId
          }).then((res) => {
            this.$alert('解锁成功', {
              confirmButtonText: '确定'
            });
            this.resetUserList();//重置当前用户列表
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      }
    }
  }
</script>


<style lang="scss">
  #userList {
    .cf:after, .cf::after {
      content: '';
      display: block;
      clear: both;
    }

    .el-col {
      border-radius: 4px;
    }

    .grid-content {
      margin: 30px;
      border-radius: 4px;
      background: white;
      padding-bottom: 20px;

      h4 {
        border-bottom: 2px solid #F1F1F1;
        margin: 0 20px;
        padding: 10px 0;
      }

      .userHandle {
        padding: 15px 20px;
        line-height: 40px;

        .handleLeft {
          float: left;
        }

        .handleRight {
          float: right;
        }
      }

      .el-button.is-round {
        border-radius: 6px;
      }

      .el-input {
        width: auto
      }
    }

    .gridLeft {
      margin-right: 2px;

      .el-tree {
        display: inline-block;
        width: 70%;
      }
    }

    .gridRight {
      margin-left: 2px;

      .el-pagination {
        margin-top: 20px;
      }
    }

    .row-bg {
      padding: 10px 0;
      background-color: #f9fafc;
    }
  }

</style>


